package com.woniuxy.woniubook.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.woniubook.entity.Book;
import com.woniuxy.woniubook.entity.User;
import com.woniuxy.woniubook.service.OrderService;
import com.woniuxy.woniubook.service.UserService;
import com.woniuxy.woniubook.uitl.CookieUtil;
import com.woniuxy.woniubook.uitl.JwtUtils;
import com.woniuxy.woniubook.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wugd
 * @since 2022-11-16 02:13:11
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    UserService userService ;


    @Autowired
    OrderService orderService ;

    @RequestMapping("/addOrder")
    public String addOrder(HttpServletRequest request,Long addressId ,
                            @RequestParam(value = "bookIds[]") Long[] bookIds){
        try {
            //查询出用户对象
            User user = this.getUser(request);
            String result = orderService.addOrder(user,addressId,bookIds);
            return result ;
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }

    }


    private User getUser(HttpServletRequest request){
        // 获取 用户的ID
        String user_token = CookieUtil.getToken(request, "user_token");
        String account = JwtUtils.getAccount(user_token);
        //查询用户对象
        User user = userService.getUserByName(account);
        return user ;
    }

    @RequestMapping("/orderList")
    public Page<OrderVo> orderPage(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "2")Integer size,
            String orderNum,HttpServletRequest request){
        User user = this.getUser(request);

        Page<OrderVo> page = orderService.getOrderByPage(now,size,orderNum,user.getId());
        return  page;
    }
    @RequestMapping("/cancelOrder")
    public String cancelOrder(long oid,HttpServletRequest request){
        try {
           // User user = this.getUser(request);
            return orderService.cancelOrder(oid);
        }catch (Exception e){
            e.printStackTrace();
            return "取消失败!" ;
        }
    }

}

